package com.hbplat.shardingsphere.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class UrlDownFileUtil {


    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static File downLoadFromUrl(String urlStr, String fileName, String savePath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File file = null;
        try {
            if (StringUtil.isNotEmpty(urlStr)) {
                File file1 = new File(savePath);
                if(!file1.exists()){
                    file1.mkdirs();
                }
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                // 解决乱码问题
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
                connection.connect();
                InputStream is = connection.getInputStream();
                bis = new BufferedInputStream(is);
                file = new File(savePath + File.separator + fileName);
                FileOutputStream fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                int b = 0;
                byte[] byArr = new byte[1024 * 1024];
                while ((b = bis.read(byArr)) != -1) {
                    bos.write(byArr, 0, b);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    public static byte[] createZip(String srcSource, String dir) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        // 将目标文件打包成zip导出
        File file = new File(srcSource);
        a(zip, file, dir);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 返回附件路径
     * @param srcSource
     * @param dir
     * @return
     * @throws Exception
     */
    public static String createZip2(String srcSource, String dir) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        // 将目标文件打包成zip导出
        File file = new File(srcSource);
        a(zip, file, dir);
        IOUtils.closeQuietly(zip);
        return file.getPath();
    }


    public static void a(ZipOutputStream zip, File file, String dir) throws Exception {
        // 如果当前的是文件夹，则进行进一步处理
        try {
            if (file.isDirectory()) {
                // 得到文件列表信息
                File[] files = file.listFiles();
                // 将文件夹添加到下一级打包目录
                zip.putNextEntry(new ZipEntry(dir + "/"));
                dir = dir.length() == 0 ? "" : dir + "/";
                // 循环将文件夹中的文件打包
                for (int i = 0; i < files.length; i++) {
                    a(zip, files[i], dir + files[i].getName());
                }
            } else {
                // 当前的是文件，打包处理文件输入流
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                ZipEntry entry = new ZipEntry(dir);
                zip.putNextEntry(entry);
                zip.write(FileUtils.readFileToByteArray(file));
                IOUtils.closeQuietly(bis);
            }
        } catch (Exception e) {
            // TODO: handle exception
            zip.flush();
            zip.close();
        }
    }


    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}
